/**
 * 
 */
package com.gopay.webtest.controller.base;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.exception.WebTestException;

/**
 * @BaseController.java
 * @author pengxw
 * @2013-7-26 上午11:06:47  www.gopay.com.cn Inc.All rights reserved.
 */
public abstract class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    
    protected final String ERROR_PAGE = "system.error.webtest.def";
  
    /**
     * 预防表单重复提交令牌,保存在session和request中,验证后从session删除
     */
    public static String SUBMIT_TOKEN = "submitToken";

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
    }
    
    /**
     * 获取request域的数据 如果值为：null,"null","undefined" 则返回 "".
     * 
     * @param par
     * @return
     */
    protected String getParameter(String par) {
        String val = getRequest().getParameter(par);
        if (StringUtils.isBlank(val)
                || StringUtils.equalsIgnoreCase(val, "null")
                || StringUtils.endsWithIgnoreCase(val, "undefined")) {
            return "";
        }
        return StringUtils.trim(val);
    }
    
    /**
     * 获取request域的数据 如果值为：null,"null","undefined" 则返回 "".
     * 
     * @param par
     * @return
     */
    protected String getVerifyCode() {
        String val = getRequest().getParameter("verficationCode");
        if (StringUtils.isBlank(val)
                || StringUtils.equalsIgnoreCase(val, "null")
                || StringUtils.endsWithIgnoreCase(val, "undefined")) {
            return "11111aaaaa";
        }
        return StringUtils.trim(val);
    }

    /**
     * 安装预防表单重复提交令牌
     * 
     * @param mv
     */
    protected void installSubmitToken(ModelAndView mv) {
        // 生成令牌
        String token = String.valueOf(UUID.randomUUID().toString());
        // 将令牌放入session中
        getRequest().getSession().setAttribute(SUBMIT_TOKEN, token);
        // 将令牌放入request中
        mv.addObject(SUBMIT_TOKEN, token);
    }

    /**
     * 校验预防表单重复提交令牌
     * 
     * @throws GopayException
     */
    protected void checkSubmitToken() throws WebTestException {
        // 从请求参数中获取令牌
        String token = getRequest().getParameter(SUBMIT_TOKEN);

        // 从session中获取令牌
        String t = (String) getRequest().getSession().getAttribute(SUBMIT_TOKEN);
        // 从session中删除令牌
        getRequest().getSession().removeAttribute(SUBMIT_TOKEN);

        // 验证请求参数中的令牌是否和session中保存的一致
        if (token == null || !token.equals(t)) {
            throw new WebTestException("error", "该网页已过期!请重试");
        }
    }
    
    /**
     * 获取项目路径
     * @return
     */
    protected String getRootPath(){
        return this.getRequest().getSession().getServletContext().getRealPath("/");
    }
    
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String errorMsg = sw.toString();
        logger.error("[handleException]进行Controller处理时出现错误：{}", errorMsg);

        ModelAndView mav = new ModelAndView(ERROR_PAGE);
        mav.addObject("errMsg", errorMsg);

        return mav;
    }
    
    public  String getRemoteRealIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 当通过代理访问时，x-forwarded-for获取的IP地址格式：clientIP, proxy1IP, proxy2IP, ……
        // 添加过滤处理，只获取客户真实IP，过滤掉代理服务器IP
        if (ip == null) {
            ip = "";
        }
        String ips[] = ip.split(",");
        for (int i = 0; i < ips.length; i++) {
            String realIP = ips[i] == null ? "" : ips[i].trim();
            if (!"unknown".equals(realIP) && !"".equals(realIP)) {
                ip = realIP;
                break;
            }
        }

        return ip;
    }
}
